<template>
  <div>
    <!-- 头部 -->
    <a-form
      ref="searchRef"
      :rules="rules"
      :model="searchForm"
      :hideRequiredMark="true"
      style="margin-bottom: 20px"
    >
      <a-row>
        <a-col :span="6" :offset="1">
          <a-form-item name="saleValue" label="耗材编号">
            <a-input
              placeholder="请输入耗材编号"
              v-model:value="searchForm.number"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item name="saleValue" label="耗材名称">
            <a-input
              placeholder="请输入耗材名称"
              v-model:value="searchForm.name"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6" :offset="1">
          <a-form-item name="saleValue" label="所属服务">
            <a-input
              placeholder="请输入所属服务"
              v-model:value="searchForm.serviceName"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item name="status" label="状态">
            <a-select
              ref="select"
              v-model:value="searchForm.status"
              @focus="focus"
              @change="selectXZname"
              placeholder=""
              style="width: 150px"
            >
              <a-select-option
                v-for="item in saleStatusOptions"
                :value="item.id"
                :key="item.id"
                >{{ item.name }}</a-select-option
              >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4" :offset="1">
          <a-button type="primary" @click="search" class="d-a-center"
            >搜索</a-button
          ></a-col
        >
      </a-row>
    </a-form>

    <!-- 列表 -->
    <a-table
      :columns="columns"
      :data-source="list"
      bordered
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #classify="{ record }">
        <div v-if="record.serviceId">
          {{ record.serviceId }}
        </div>
      </template>
      <template #status="{ record, index }">
        {{ ["已上架", "已下架", "待审核", "已拒绝"][record.status] }}
      </template>
      <template #operation="{ record }">
        <a-button type="link" @click="look(record)" v-has="{ a: $route, b: 1 }"
          >查看</a-button
        >
        <a-button
          type="link"
          @click="edit(record)"
          v-if="record.status == 2"
          v-has="{ a: $route, b: 2 }"
          >审核</a-button
        >
      </template>
    </a-table>
    <!-- 多项删除 -->

    <div>
      <!-- 弹窗 -->
      <a-modal
        v-if="visible"
        width="60%"
        wrap-class-name="full-modal"
        :visible="visible"
        :title="modalTitle"
        :footer="null"
        @cancel="cancel"
      >
        <!--  okText="通过"
        :cancelText="cancelText"
        @ok="save"
        @cancel="cancel" 
        :destroyOnClose="true"
      
      -->
        <a-form
          ref="formRef"
          :rules="rules1"
          :model="form"
          :hideRequiredMark="true"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item label="耗材名称" name="consumableName">
            <a-input
              v-model:value="form.consumableName"
              placeholder=""
            ></a-input>
          </a-form-item>
          <a-form-item label="市场价格" name="bazaarPrice">
            <a-input
              v-model:value="form.bazaarPrice"
              placeholder="请输入耗材包市场价"
            ></a-input>
          </a-form-item>
          <a-form-item label="销售价格" name="sellPrice">
            <a-input v-model:value="form.sellPrice" placeholder=""></a-input>
          </a-form-item>
          <a-form-item label="所属服务" name="serviceName">
            <a-input v-model:value="form.serviceName" placeholder=""></a-input>
          </a-form-item>
          <a-form-item label="耗材明细" name="consumableLists">
            <a-input
              v-model:value="form.consumableLists"
              placeholder=""
            ></a-input>
          </a-form-item>
          <a-form-item label="耗材包编号" name="id">
            <a-input v-model:value="form.id" placeholder=""></a-input>
          </a-form-item>
          <a-form-item
            label="拒绝原因"
            v-if="form.type == 'deny'"
            name="denyCause"
          >
            <a-input v-model:value="form.denyCause" placeholder=""></a-input>
          </a-form-item>
        </a-form>
        <a-row justify="center" :gutter="10">
          <a-col :span="4">
            <a-button
              type="info"
              v-if="cancelText == '关闭'"
              @click="cancel"
              class="d-a-center"
              >{{ cancelText }}</a-button
            >
            <a-button type="info" v-else @click="jujue">{{
              cancelText
            }}</a-button>
          </a-col>
          <a-col v-if="cancelText == '拒绝' && editType != 2" :span="4">
            <a-button type="primary" @click="save(form.id)" class="d-a-center"
              >通过</a-button
            >
          </a-col>
        </a-row>
        <!-- <a-input placeholder="请输入分类名称" v-model:value="title" @pressEnter="save"></a-input> -->
      </a-modal>
      <!-- 关联门店 -->
      <a-modal
        :visible="storeVisible"
        @ok="associateStore"
        @cancel="storeVisible = false"
        zIndex="9999"
        okText="确定"
      >
        <a-form ref="storeFormRef" :rules="rules1">
          <a-form-item
            label="
拒绝原因"
            name="consumableLists"
          >
            <a-input v-model:value="denyCause" placeholder=""></a-input>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>
<script>
import {
  reactive,
  ref,
  computed,
  createVNode,
  watch,
  toRefs,
  unref,
  toRaw,
  isReactive,
  toRef,
} from "vue";
import {
  CheckOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { Modal, message } from "ant-design-vue";
import {
  selectConsumableBagByDto,
  upOrDownConsumableBag,
  selectAllDetail,
  updateAndAddConsumableBag,
  updateConsumableStatus,
  deleteConsumableBag,
} from "@/api/consume/index.js";
import { selectAllService, selectAllType } from "@/api/service/index.js";
import { deleteObjBlank } from "@/assets/js/common.js";
import { useModal } from "@/hooks"

export default {
  setup() {
    const searchRef = ref("");
    const formRef = ref("");

    const data = reactive({
      list: [],
      loading: true,
      visible: false,
      serviceList: [], //分类列表
      detaiList: [],
      consumables: [], //默认绑定ID即可
      statusAct: 0,
      searchForm: {},
      typeList: [],
      form: { isDele: 0 },
      value: [], //分类-这个远程加载的数据好像不可以哎
      defaultValue: [],
      cancelText: "拒绝",
      storeVisible: false,
      denyCause: "",
    });

    const title = ref(""); //分类名称

    let modalTitle = ref("新增耗材");
    const rules = {
      //  portValue: [{ required: true, message: '请选择端口!', trigger: 'change'}],
      //  inputValue: [{ required: true, message: '请输入搜索内容!', trigger: 'blur'}],
    };
    const rules1 = {
      name: [{ required: true, message: "请输入耗材名称!" }],
      sellPrice: [{ required: true, message: "请输入销售价!" }],
      serviceId: [{ required: true, message: "请输入服务类型!" }],
      typeId: [{ required: true, message: "请输入服务分类!" }],
      bazaarPrice: [{ required: true, message: "请输入市场价格!" }],
      bagNumber: [{ required: true, message: "请输入耗材编号!" }],
      // value: [{ required: true, message: "请选择耗材分类!" }],
    };

    // 分页器
    const page = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
    });

    const saleStatusOptions = reactive([
      {
        name: "已上架",
        id: 0,
      },
      {
        name: "已下架",
        id: 1,
      },
      {
        name: "待审核",
        id: 2,
      },
      {
        name: "已拒绝",
        id: 3,
      },
    ]);
    const consumeOptions = reactive([
      {
        name: "耗材名称",
        id: 1,
      },
      {
        name: "耗材分类",
        id: 1,
      },
    ]);
    const delListId = ref([]); //删除数组ID集合
    const chooseStatus = (status, index) => {
      data.statusAct = index;
      data.searchForm.status = status;
      page.current = 1;
      init();
    };
    // 查询
    const search = () => {
      page.current = 1;
      init();
    };
    const columns = [
      {
        title: "耗材编号",
        dataIndex: "id",
        className: "table",
      },
      {
        title: "耗材名称",
        dataIndex: "consumableName",
        className: "table",
      },
      {
        title: "市场价格",
        dataIndex: "bazaarPrice",
        className: "table",
      },
      {
        title: "销售价格",
        dataIndex: "sellPrice",
        className: "table",
      },
      {
        title: "所属服务",
        dataIndex: "serviceName",
        // dataIndex: "serveName",
        className: "table",
      },
      {
        title: "状态",
        dataIndex: "status",
        className: "table",
        slots: {
          customRender: "status",
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        className: "table",
        slots: {
          customRender: "operation",
        },
      },
    ];

    // 分页器
    const pagination = computed(() => ({
      current: page.current,
      pageSize: page.pageSize,
      pageSizeOptions: ["10", "20", "30"],
      showTotal: (total, range) => {
        return "共" + total + "条";
      },
      total: page.total,
      showQuickJumper: true,
      showSizeChanger: true,
    }));

    // 分页器改变的时候
    const handleTableChange = (pagination, filters, sorter) => {
      console.log(pagination, "当前分页");
      page.current = pagination.current;
      page.pageSize = pagination.pageSize;

      // 请求列表接口
      init();
    };
    const cancel = () => {
      data.visible = false;
      // title.value = "";
      data.form = {};
    };
    const jujue = () => {
      data.storeVisible = true;
    };

    const associateStore = async () => {
      if (!data.denyCause) {
        message.error("请输入原因");
        return;
      }
      data.storeVisible = false;
      let res = await updateConsumableStatus({
        id: data.form.id,
        status: 3,
        denyCause: data.denyCause,
      });
      if (res.success) {
        message.success("操作成功");
        data.visible = false;

        init();
      }
    };
    // 新增
    const add = () => {
      data.visible = true;
    };
    const edit = async (item) => {
      // item.typeId = String(item.typeId);
      console.log(item, "item");
      item.consumableLists = item.consumableList[0].bleName;
      data.form = item;
      modalTitle.value = "审核";
      data.cancelText = "拒绝";
      data.visible = true;
    };
    const look = async (item) => {
      // item.typeId = String(item.typeId);
      console.log(item, "item");
      item.consumableLists = item.consumableList[0].bleName;
      data.form = item;
      if (item.status == 3) {
        data.form.type = "deny";
      }
      modalTitle.value = "审核";
      data.cancelText = "关闭";

      data.visible = true;
    };
    const Typename = (id) => {
      let item = data.typeList.find((el) => el.id == id);
      console.log(item, "分类名字是");
      return item;
    };

    const serviceName = (id) => {
      let list = data.serviceList.find((el) => el.id == id);
      if (list.serviceName) {
        // return list.serveName;
        return list;
      }
    };
    const save = (id) => {
      const {closeModal} = useModal.confirm({
        title: () => "确认通过此耗材上架审核吗?",
        icon: () => createVNode(QuestionCircleOutlined),
        onOk: async () => {
          let res = await updateConsumableStatus({ id, status: 0 });
          if (res.success) {
            data.visible = false;
            message.success("操作成功");
            init();
            closeModal()
          }
        },

        class: "test",
      });
    };

    const selectConsume = (e) => {
      console.log(e);
    };
    const selectService = (e) => {
      // console.log(e, "服务类型");s
    };
    const selectType = (e) => {};

    // 全选反选
    const rowSelection = ref({
      checkStrictly: false,
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(
          `selectedRowKeys: ${selectedRowKeys}`,
          "selectedRows: ",
          selectedRows
        );
        delListId.value = selectedRowKeys;
      },
      onSelect: (record, selected, selectedRows) => {
        //console.log(record, selected, selectedRows,'选择多项');
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        //console.log(selected, selectedRows, changeRows,'全选操作');
        // 数组项
      },
    });
    

    
    initServiceList();

    init();
    initAllDetailList();
    async function init() {
      let obj = {
        pageNum: page.current,
        pageSize: page.pageSize,
        ...data.searchForm,
      };
      let res = await selectConsumableBagByDto(obj);
      if (res.success) {
        res.object.list.map((el) => (el.key = el.id));
        data.list = res.object.list;
        // data.list.forEach(el=>{
        // })
        data.loading = false;
        page.total = res.object.total;
      }
    }
    // 一级分类
    async function initServiceList() {
      let obj = {
        pageNum: 1,
        pageSize: 80,
      };
      let res1 = await selectAllType(obj);
      if (res1.success) {
        res1.object.records.map((el) => (el.isLeaf = false)); //id是string类型的
        data.typeList = res1.object.records;
      }
    }
    async function initAllDetailList() {
      let res = await selectAllDetail();
      if (res.success) {
        data.detaiList = res.object;
      }
    }

    const loadData = async (selectedOptions) => {
      console.log("点击了选择", selectedOptions);
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true; // load options lazily

      let obj = {
        pageNum: 1,
        pageSize: 80,
        typeId: selectedOptions[0].id,
      };
      let res = await selectAllService(obj);
      if (res.success) {
        targetOption.loading = false;
        res.object.records.map((el) => (el.name = el.serveName));
        targetOption.children = res.object.records;

        data.typeList = [...data.typeList];
      }
    };
    return {
      ...toRefs(data),
      saleStatusOptions,
      consumeOptions,
      searchRef,
      modalTitle,
      formRef,
      rules,
      rules1,
      columns,
      pagination,
      title,
      labelCol: { style: { width: "150px" } },
      wrapperCol: { span: 14 },
      handleTableChange,
      search,
      add,
      save,
      cancel,
      edit,
      rowSelection,
      serviceName,
      selectConsume,
      selectService,
      chooseStatus,
      Typename,
      selectType,
      loadData,
      look,
      associateStore,
      jujue,
    };
  },

  components: {
    CheckOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    QuestionCircleOutlined,
  },
};
</script>

<style scoped lang="less">
.act {
  color: #2a9d8f;
}
</style>
